package org.jeecg.modules.cw.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.modules.cw.entity.*;
import org.jeecg.modules.cw.service.*;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.cw.vo.CwGyjfzcTjPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 公用经费支出提交表
 * @Author: jeecg-boot
 * @Date:   2025-09-12
 * @Version: V1.0
 */
@Api(tags="公用经费支出提交表")
@RestController
@RequestMapping("/cw/cwGyjfzcTj")
@Slf4j
public class CwGyjfzcTjController {
	@Autowired
	private ICwGyjfzcTjService cwGyjfzcTjService;
	@Autowired
	private ICwGyjfzcService cwGyjfzcService;
	 @Autowired
	 private ICwApprovalMessageService cwApprovalMessageService;
	 @Autowired
	 private ICwJbszqkzbService cwJbszqkzbService;
	 @Autowired
	 private ICwJbszqkzbZhuService cwJbszqkzbZhuService;
	 @Autowired
	 private ISysDepartService sysDepartService;
	 @Autowired
	 private ISysBaseAPI iSysBaseAPI;
	/**
	 * 分页列表查询
	 *
	 * @param cwGyjfzcTj
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "公用经费支出提交表-分页列表查询")
	@ApiOperation(value="公用经费支出提交表-分页列表查询", notes="公用经费支出提交表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CwGyjfzcTj>> queryPageList(CwGyjfzcTj cwGyjfzcTj,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CwGyjfzcTj> queryWrapper = QueryGenerator.initQueryWrapper(cwGyjfzcTj, req.getParameterMap());
		Page<CwGyjfzcTj> page = new Page<CwGyjfzcTj>(pageNo, pageSize);
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if (user == null || StringUtils.isEmpty(user.getId())) {
			return Result.error("未获取到登录用户信息，查询失败");
		}
		String currentUserId = user.getId();

		List<String> adminUserIds = Arrays.asList(
				"1962681660831399937",  // 第一个特权用户ID
				"1962696194421923842"   // 第二个特权用户ID
		);

		if (adminUserIds.contains(currentUserId)) {
			if ("1962681660831399937".equals(currentUserId)) {
				queryWrapper.in("state", "待审批", "通过", "驳回");
			} else if ("1962696194421923842".equals(currentUserId)) {
				queryWrapper.in("state", "待审批", "通过", "驳回");
			}
		} else {
			queryWrapper.eq("main_id", currentUserId);
		}
		IPage<CwGyjfzcTj> pageList = cwGyjfzcTjService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	 /**
	  * 审批
	  * @param id 记录ID
	  * @return 处理结果
	  */
	 @AutoLog(value = "审批-审批")
	 @ApiOperation(value="审批-审批", notes="审批-审批")
	 @RequestMapping(value = "/approval", method = {RequestMethod.PUT, RequestMethod.POST})
	 public Result<String> approval(@RequestParam String id,
									@RequestParam String approvalResult,
									@RequestParam String approvalRemark) {
		 //获取当前用户名
		 LoginUser user= (LoginUser)SecurityUtils.getSubject().getPrincipal();
		 String userId=user.getId();
		 CwGyjfzcTj byId = cwGyjfzcTjService.getById(id);
		 CwApprovalMessage cwApprovalMessage = new CwApprovalMessage();
		 cwApprovalMessage.setMainId(byId.getId());
		 cwApprovalMessage.setApprovalMessage(approvalRemark);
		 cwApprovalMessage.setApprovalTime(new Date());
		 cwApprovalMessage.setApprover(userId);
		 cwApprovalMessage.setState(approvalResult);
		 cwApprovalMessage.setSpr(user.getRealname());
		 cwApprovalMessageService.save(cwApprovalMessage);
		 byId.setState(approvalResult);
		 byId.setApprovalTime(new Date());
		 cwGyjfzcTjService.updateById(byId);

		 return Result.OK("提交成功");
	 }

	 /**
	  * 提交处理
	  * @param id 记录ID
	  * @return 处理结果
	  */
	 @AutoLog(value = "提交-提交")
	 @ApiOperation(value="提交-提交", notes="提交-提交")
	 @RequestMapping(value = "/tj", method = {RequestMethod.PUT, RequestMethod.POST})
	 public Result<String> tj(@RequestParam String id) {
		 //获取当前用户名
		 LoginUser user= (LoginUser)SecurityUtils.getSubject().getPrincipal();
		 String userName=user.getRealname();
		 log.info(id);
		 CwGyjfzcTj byId = cwGyjfzcTjService.getById(id);
		 byId.setState("待审批");
		 cwGyjfzcTjService.updateById(byId);
		 return Result.OK("提交成功");
	 }
	/**
	 *   添加
	 *
	 * @param cwGyjfzcTjPage
	 * @return
	 */
	@AutoLog(value = "公用经费支出提交表-添加")
	@ApiOperation(value="公用经费支出提交表-添加", notes="公用经费支出提交表-添加")
    //@RequiresPermissions("org.jeecg.modules:cw_gyjfzc_tj:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CwGyjfzcTjPage cwGyjfzcTjPage) {
		CwGyjfzcTj cwGyjfzcTj = new CwGyjfzcTj();
		BeanUtils.copyProperties(cwGyjfzcTjPage, cwGyjfzcTj);

		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String departIdsByOrgCode = iSysBaseAPI.getDepartIdsByOrgCode(user.getOrgCode());
		SysDepart byId = sysDepartService.getById(departIdsByOrgCode);
		String departName = byId.getDepartName();
		cwGyjfzcTj.setUnit(departName);
		cwGyjfzcTj.setMainId(user.getId());

		for (CwGyjfzc cwZfcgb : cwGyjfzcTjPage.getCwGyjfzcList()) {
			//添加  单位，年度，用户
			cwZfcgb.setUnit(cwGyjfzcTj.getUnit());
			cwZfcgb.setYear(cwGyjfzcTjPage.getYear());
			cwZfcgb.setUserId(user.getId());
		}
		cwGyjfzcTj.setState("待提交");
		cwGyjfzcTjService.saveMain(cwGyjfzcTj, cwGyjfzcTjPage.getCwGyjfzcList());

		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param cwGyjfzcTjPage
	 * @return
	 */
	@AutoLog(value = "公用经费支出提交表-编辑")
	@ApiOperation(value="公用经费支出提交表-编辑", notes="公用经费支出提交表-编辑")
    //@RequiresPermissions("org.jeecg.modules:cw_gyjfzc_tj:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CwGyjfzcTjPage cwGyjfzcTjPage) {
		CwGyjfzcTj cwGyjfzcTj = new CwGyjfzcTj();
		BeanUtils.copyProperties(cwGyjfzcTjPage, cwGyjfzcTj);
		CwGyjfzcTj cwGyjfzcTjEntity = cwGyjfzcTjService.getById(cwGyjfzcTj.getId());
		if(cwGyjfzcTjEntity==null) {
			return Result.error("未找到对应数据");
		}
		LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String id = user.getId();
		for (CwGyjfzc cwGyjfzc : cwGyjfzcTjPage.getCwGyjfzcList()) {
			cwGyjfzc.setUnit(cwGyjfzcTj.getUnit());
			cwGyjfzc.setYear(cwGyjfzcTj.getYear());
			cwGyjfzc.setUserId(id);
		}

		cwGyjfzcTjService.updateMain(cwGyjfzcTj, cwGyjfzcTjPage.getCwGyjfzcList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "公用经费支出提交表-通过id删除")
	@ApiOperation(value="公用经费支出提交表-通过id删除", notes="公用经费支出提交表-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:cw_gyjfzc_tj:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		cwGyjfzcTjService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "公用经费支出提交表-批量删除")
	@ApiOperation(value="公用经费支出提交表-批量删除", notes="公用经费支出提交表-批量删除")
    //@RequiresPermissions("org.jeecg.modules:cw_gyjfzc_tj:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.cwGyjfzcTjService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "公用经费支出提交表-通过id查询")
	@ApiOperation(value="公用经费支出提交表-通过id查询", notes="公用经费支出提交表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CwGyjfzcTj> queryById(@RequestParam(name="id",required=true) String id) {
		CwGyjfzcTj cwGyjfzcTj = cwGyjfzcTjService.getById(id);
		if(cwGyjfzcTj==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(cwGyjfzcTj);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "公用经费支出表-通过主表ID查询")
	@ApiOperation(value="公用经费支出表-通过主表ID查询", notes="公用经费支出表-通过主表ID查询")
	@GetMapping(value = "/queryCwGyjfzcByMainId")
	public Result<IPage<CwGyjfzc>> queryCwGyjfzcListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CwGyjfzc> cwGyjfzcList = cwGyjfzcService.selectByMainId(id);
		IPage <CwGyjfzc> page = new Page<>();
		page.setRecords(cwGyjfzcList);
		page.setTotal(cwGyjfzcList.size());
		return Result.OK(page);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param cwGyjfzcTj
    */
    //@RequiresPermissions("org.jeecg.modules:cw_gyjfzc_tj:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CwGyjfzcTj cwGyjfzcTj) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<CwGyjfzcTj> queryWrapper = QueryGenerator.initQueryWrapper(cwGyjfzcTj, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

     //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
           List<String> selectionList = Arrays.asList(selections.split(","));
           queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<CwGyjfzcTj>  cwGyjfzcTjList = cwGyjfzcTjService.list(queryWrapper);

      // Step.3 组装pageList
      List<CwGyjfzcTjPage> pageList = new ArrayList<CwGyjfzcTjPage>();
      for (CwGyjfzcTj main : cwGyjfzcTjList) {
          CwGyjfzcTjPage vo = new CwGyjfzcTjPage();
          BeanUtils.copyProperties(main, vo);
          List<CwGyjfzc> cwGyjfzcList = cwGyjfzcService.selectByMainId(main.getId());
          vo.setCwGyjfzcList(cwGyjfzcList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "公用经费支出提交表列表");
      mv.addObject(NormalExcelConstants.CLASS, CwGyjfzcTjPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("公用经费支出提交表数据", "导出人:"+sysUser.getRealname(), "公用经费支出提交表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("org.jeecg.modules:cw_gyjfzc_tj:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<CwGyjfzcTjPage> list = ExcelImportUtil.importExcel(file.getInputStream(), CwGyjfzcTjPage.class, params);
              for (CwGyjfzcTjPage page : list) {
                  CwGyjfzcTj po = new CwGyjfzcTj();
                  BeanUtils.copyProperties(page, po);
                  cwGyjfzcTjService.saveMain(po, page.getCwGyjfzcList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
